package com.lian.community.util;


import com.lian.community.entity.mail.EmailAddress;
import org.hibernate.validator.constraints.Email;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Pattern;

public class MailUtil {

    private static Pattern mailPattern = Pattern.compile("^[0-9a-zA-Z_]+@[0-9a-zA-Z]+\\.com$");

    private static final String PROTOCAL = "smtp";
    private static final String EMAIL_SMTP_HOST = "smtpdm.aliyun.com";

    private static final Properties props;

    static
    {
        props = new Properties();
        props.setProperty("mail.transport.protocal", PROTOCAL);
        props.setProperty("mail.smtp.host", EMAIL_SMTP_HOST);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.timeout", "100000");
        props.setProperty("mail.smtp.connectiontimeout", "100000");
//		 props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.port", "25");
    }

    public static void sendEmail(String username, String password, com.lian.community.entity.mail.Email email) throws UnsupportedEncodingException, MessagingException
    {
        Session session = Session.getInstance(props);
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom(new InternetAddress(email.getFrom().getAddress(), email.getFrom().getNickName(), email.getEncoding()));
        for(EmailAddress address : email.getTo())
        {
            mimeMessage.addRecipient(RecipientType.TO, new InternetAddress(address.getAddress(), address.getNickName(), email.getEncoding()));
        }
        mimeMessage.setSubject(email.getTitle(), email.getEncoding());
        mimeMessage.setContent(email.getContent(), email.getContentType());
        mimeMessage.setSentDate(new Date());
        mimeMessage.saveChanges();
        Transport transport = session.getTransport();
        transport.connect(username, password);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    }

    public static boolean isMailAddress(String email)
    {
        return mailPattern.matcher(email).matches();
    }
}
